package at.fhooe.mcm12.java.serializer;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import org.xml.sax.InputSource;

public class XMLWriter extends AWriter {
	
	public XMLWriter() {
		m_fileExt = ".xml";
		m_worker = new Thread(this);
	
		start();
	}

	public static Element getElement(String[] _tags, String[] _values) {
		Element elem = new Element("log");
		Element child;
		for (int i = 0; i < _tags.length; i++) {
			child = new Element(_tags[i]);
			child.addContent(_values[i]);
			elem.addContent(child);
		}
		return elem;
	}

	@Override
	public void write(WriterQueueElement _elem) {
		String file = _elem.getFile();
		try {
			file += m_fileExt;
			File f = new File(file);

			final File parent_directory = f.getParentFile();
			if (null != parent_directory) {
				// Create directory structure
				parent_directory.mkdirs();
			}

			Document doc;
			if (!f.exists()) {// create blank xml file in case it doesn't exist
				doc = new Document();
				doc.addContent(new Element("logs"));
			} else {
				SAXBuilder sxbuild = new SAXBuilder();
				InputSource is = new InputSource(file);
				doc = sxbuild.build(is);
			}
			Element root = doc.getRootElement();
			// append new xml element to the document
			root.addContent(getElement(_elem.getTags(), _elem.getValues()));
			// format the xml and write it out
			XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
			
			FileWriter writer=new FileWriter(file);
			outputter.output(doc, writer);
			writer.flush();
			writer.close();
			
		} catch (JDOMException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
